package xzit.gcxy.xxhzx.zhh.dao.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import xzit.gcxy.xxhzx.zhh.dao.SystemDao;
import xzit.gcxy.xxhzx.zhh.entity.APPNavigatorVO;
import xzit.gcxy.xxhzx.zhh.entity.ManagedAccountVO;
import xzit.gcxy.xxhzx.zhh.entity.TeacherSWTotalVO;
import xzit.gcxy.xxhzx.zhh.util.InstituteUtil;

@Repository
public class SystemDaoImpl extends BaseDaoImpl implements SystemDao {

	public ManagedAccountVO getUserByNameAndPassword(ManagedAccountVO user) {
		Md5Hash md5Hash = new Md5Hash(user.getPassword());
		String password = md5Hash.toHex();
		String query = "from ManagedAccountVO u where u.username = :username and u.password=:passowrd";
		Query queryObject = getSession().createQuery(query);
		queryObject.setParameter("username", user.getUsername());
		queryObject.setParameter("passowrd", password);
		List<ManagedAccountVO> users = queryObject.list();
		if (users != null && users.size() > 0) {
			return users.get(0);
		}

		return null;
	}

	public <T> T findUniqueByProperty(Class<T> entityClass, String propertyName, Object value) {
		return (T) createCriteria(entityClass, Restrictions.eq(propertyName, value)).uniqueResult();
	}

	private <T> Criteria createCriteria(Class<T> entityClass, Criterion... criterions) {
		Criteria criteria = getSession().createCriteria(entityClass);
		for (Criterion c : criterions) {
			criteria.add(c);
		}
		return criteria;
	}

	public static void main(String[] args) {
		Md5Hash md5Hash = new Md5Hash("admin");
		String password = md5Hash.toHex();
		System.out.println(password);
	}

	public APPNavigatorVO getAPPRootByNameAndPassword() {
		String query = "from APPNavigatorVO u where u.id = 1";
		Query queryObject = getSession().createQuery(query);
		List<APPNavigatorVO> users = queryObject.list();
		if (users != null && users.size() > 0) {
			return users.get(0);
		}
		return null;
	}

	public List<TeacherSWTotalVO> getTotalScore4Teacher() {
		List<TeacherSWTotalVO> vos = new ArrayList();
		;
		String query = "select u.teacherInfoVO.gonghao as gonghao,u.teacherInfoVO.realname as realname,u.teacherInfoVO.business as business,sum(u.score) as total from ScienceWorkDetailVO u where u.scienceworktype.instituteid = "
				+ InstituteUtil.getCurrentInstituteId() + " group by u.teacherInfoVO.gonghao";
		Query queryObject = getSession().createQuery(query);
		List result = queryObject.list();
		Iterator it = result.iterator();
		while (it.hasNext()) {
			Object[] tuple = (Object[]) it.next();
			TeacherSWTotalVO vo = new TeacherSWTotalVO((String) tuple[0], (String) tuple[1], (String) tuple[2],
					(Double) tuple[3]);
			vos.add(vo);
		}

		return vos;
	}
}
